<?php

/*
 * Copyright (C) 2014 koodo@qq.com.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301  USA
 */

$_TIME = time();

class Wechat {

    private $serverRoot = "http://112.124.44.172/wshop/";
    
    /**
     * request user openid
     * @var <string>
     */
    public $openID = null;
    
    /**
     * wechat origin id
     * @var <string>
     */
    private $serverID = null;
    
    /**
     * current time
     * @var <UNIX TIMESTAMP>
     */
    private $time;
    
    /**
     * mysql database
     * @var <PDO>
     */
    private $Db;

    /**
     * Wechat Class Construction method
     * @access public
     */
    public function __construct() {
        $this->Db = new Db();
        $this->time = time();
    }

    public function responseImageText($data = array()) {
        $tpl = "<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[news]]></MsgType>
        <ArticleCount>%s</ArticleCount>
        <Articles>%s</Articles>
        </xml>";

        $items = "";
        foreach ($data as $item) {
            $items .= "<item>";
            // cont
            $items .= "<Title><![CDATA[" . $item['title'] . "]]></Title>";
            $items .= "<Description><![CDATA[" . $item['desc'] . "]]></Description>";
            if ($item['url']) {
                $items .= "<Url><![CDATA[" . $item['url'] . "]]></Url>";
            }
            if ($item['picurl']) {
                $items .= "<PicUrl><![CDATA[" . $item['picurl'] . "]]></PicUrl>";
            }
            // cont
            $items .= "</item>";
        }

        echo sprintf($tpl, $this->openID, $this->serverID, $this->time, count($data), $items);
        exit(0);
    }

    // 向客户端发送文本
    public function responseText($contentStr) {

        $textTpl = "<xml> 
                    <ToUserName><![CDATA[%s]]></ToUserName> 
                    <FromUserName><![CDATA[%s]]></FromUserName> 
                    <CreateTime>%s</CreateTime> 
                    <MsgType><![CDATA[%s]]></MsgType> 
                    <Content><![CDATA[%s]]></Content> 
                    <FuncFlag>0</FuncFlag> 
                    </xml>";
        echo sprintf($textTpl, $this->openID, $this->serverID, $this->time, "text", $contentStr);

        exit(0);
    }

    // 按钮事件处理入口
    public function EventRequest($postObj) {

        // wdmin login qrcode scaning
        if ($postObj->Event == "subscribe" || $postObj->Event == "SCAN") {
            if (preg_match("/8814/is", $postObj->EventKey)) {
                include dirname(__FILE__) . '/mWdmin.php';
                $mdw = new mWdmin();
                if (preg_match("/qrscene/is", $postObj->EventKey)) {
                    $mdw->loginQrcodeScaned(preg_replace("/qrscene\_/is", "", $postObj->EventKey), $this->openID);
                } else {
                    $mdw->loginQrcodeScaned($postObj->EventKey, $this->openID);
                }
            }
        }

        /*
         * unsubscribe
         */
        if ($postObj->Event == "unsubscribe") {
            $this->Db->query("INSERT INTO wechat_subscribe_record (openid,date,dv) VALUES ('$this->openID',NOW(),-1);");
        }

        /**
         * subscribe
         */
        if ($postObj->Event == "subscribe") {
            $this->Db->query("INSERT INTO wechat_subscribe_record (openid,date,dv) VALUES ('$this->openID',NOW(),1);");
        }
    }

    // 语音处理入口
    public function VoiceRequest($postObj) {
        $this->responseText($postObj->Recognition);
    }

    // 普通文本处理入口
    public function TextRequest($Content) {
        // 获取openid请求 @Devlopment
        if (preg_match("/getopenid/", $Content)) {
            $this->responseText($this->openID);
            file_put_contents('openid', $this->openID);
        }
    }

    // 主入口
    public function handle() {
        //get post data, May be due to the different environments 
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);

        // 记录openid
        $this->openID = $postObj->FromUserName;
        // 记录服务号ID
        $this->serverID = $postObj->ToUserName;

        //extract post data 
        if (!empty($postStr)) {
            switch ($postObj->MsgType) {
                case "text" :
                    $this->TextRequest($postObj->Content);
                    break;
                case "event" :
                    $this->EventRequest($postObj);
                    break;
                case 'voice' :
                    break;
            }
        }
    }

}
